#include "gamma-manager-thread.h"

GmThread::GmThread(QObject *parent)
{
    m_rtTemperature = COLOR_TEMPERATURE_DEFAULT;
    m_timerRunTimes= 0;
    m_lastTemperature = COLOR_TEMPERATURE_DEFAULT;
    m_pSetTimer = new QTimer(this);
    m_pGmHelper = new GmHelper(this);
    m_pSetTimer->setSingleShot(false);
    m_pSetTimer->setTimerType(Qt::PreciseTimer);
    connect(m_pSetTimer, SIGNAL(timeout()), this, SLOT(doSetTimer()), Qt::QueuedConnection);
}

GmThread::~GmThread()
{
    if (m_pSetTimer) {
        delete m_pSetTimer;
        m_pSetTimer = nullptr;
    }
}

void GmThread::setBrightness(int brightness)
{
    m_brightness = brightness;
}

void GmThread::setTemperature(int temperature)
{
    m_brightness = temperature  ;
    m_timerRunTimes = 0;
    m_targetTemp = temperature;
//    this->start();
//    m_pSetTimer->start(50);
}

OutputGammaInfoList GmThread::getAllOutputGammaInfo()
{
    OutputGammaInfoList ret;

    return ret;
}

void GmThread::run()
{
    double frac;
    do {
        QTime timerStart = QTime::currentTime();
        frac = (m_timerRunTimes * 50.f) / (1000.f*USD_NIGHT_LIGHT_SMOOTH_SMEAR);
        if (qAbs(m_rtTemperature - m_targetTemp) < 10.f) {
            m_rtTemperature = m_targetTemp;
        } else {
            m_rtTemperature = (m_targetTemp - m_lastTemperature) * frac + m_lastTemperature;
        }

        m_pGmHelper->setTemperature(m_rtTemperature);
        m_lastTemperature = m_rtTemperature;
        m_timerRunTimes++;
        USD_LOG(LOG_DEBUG,"cost time:%d rtTemperature:%d",timerStart.msecsTo(QTime::currentTime()), m_rtTemperature);
        msleep(30);
    } while (m_brightness != m_rtTemperature);
}

void GmThread::doSetTimer()
{
    double frac;

    frac = (m_timerRunTimes * 100.f) / (1000.f*USD_NIGHT_LIGHT_SMOOTH_SMEAR);
    if (qAbs(m_rtTemperature - m_targetTemp) < 10.f) {
        m_rtTemperature = m_targetTemp;
    } else {
        m_rtTemperature = (m_targetTemp - m_lastTemperature) * frac + m_lastTemperature;
    }
    m_pGmHelper->setTemperature(m_rtTemperature);
    m_lastTemperature = m_rtTemperature;
    m_timerRunTimes++;
    if (m_rtTemperature == m_targetTemp) {
        this->m_pSetTimer->stop();
    }
}
